package com.wang.commons.utils;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * javaMail工具类
 */
public class MailUtil {


    /**
     * 邮件发送方法
     * @param address 发送邮箱号
     * @param consignee 接收的邮箱号，前端传入的邮箱号
     * @param authCode 发送邮箱的授权码
     * @param title 邮件标题
     * @param content 邮件正文
     */
    public static void sendMail(String address,String consignee,String authCode,String title,String content) {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol","SMTP");//设置发送邮件的协议
        properties.setProperty("mail.host","smtp.163.com");//设置发送邮件的服务器
        properties.setProperty("mail.smtp.auth","true");//设置通过验证
        Authenticator authenticator = new Authenticator(){//设置邮箱验证器
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //邮箱号，授权码
                return new PasswordAuthentication(address,authCode);
            }
        };
        //创建session对象
         Session session = Session.getInstance(properties, authenticator);
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //设置发件人
        try {
            mimeMessage.setFrom(address);
            //设置收件人
            mimeMessage.setRecipients(Message.RecipientType.TO,consignee);
            //设置主题
            mimeMessage.setSubject(title);
            //设置内容
            mimeMessage.setContent(content,"text/html;charset=utf-8");
            //发送邮件
            Transport.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}
